﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Scale2;
using System.IO.Ports;
using System.Text.RegularExpressions;
using ECS.Framework;
using ECS.DAL;
using ECS.DAL.Component;
using ECS.DAL.Entity;
using System.Threading;
using System.Data.Common;

namespace E_ICS
{
    public partial class Weight : Form
    {
        #region private properties
       private string _regOfTareGrossPallet = @"^[0-9\b]*$";
       //private int _Gross = 0;
       //private int _Net = 0;
       private int _Tare = 0;
       //private int _Pallet = 0;
       private string _weight = string.Empty;
       private double _sumResutl = 0;
       private int _debugLevel = 0;
       private Main.frmMain2 _main  = null ;
        #endregion

        #region form event
        //SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["con3"].ConnectionString);
        public Weight(Main.frmMain2 main)
        {
            InitializeComponent();
            _main = main;
        }
        private void Weight_Load(object sender, EventArgs e)
        {
            try
            {
                SetScreen();
                default_tare_weight();
                get_com_port();
  
                _debugLevel = Getdebug_level();
                //why read weight status is on OnPaint event??? it impact form responsive performance.
                //because it always call this method.
                ReadWeightStatus();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }
/// <summary>
/// SetScreen load result from DB 
/// </summary>
        private void SetScreen()
        {
            this.Text = CommonResourceString.GetResourseValue("scn_Weight_frm_name");
            label4.Text = CommonResourceString.GetResourseValue("scn_Weight_label4");
            label1.Text = CommonResourceString.GetResourseValue("scn_Weight_label1");
            label2.Text = CommonResourceString.GetResourseValue("scn_Weight_label2");
            label3.Text = CommonResourceString.GetResourseValue("scn_Weight_label3");
            btnSave.Text = CommonResourceString.GetResourseValue("scn_Weight_btnSave");
            btnCancel.Text = CommonResourceString.GetResourseValue("scn_Weight_btnCancel");
                  
          
        }
/// <summary>
/// load value debugLevel from DB for open log
/// </summary>
/// <returns></returns>
        private int Getdebug_level()
        {
            //                SELECT @v_nDB_DebugLevel = setting_value_number
            //FROM t_eics_setup
            //WHERE [type] = 'SYSTEM'
            //AND setting_name = 'APP_DEBUG_LEVEL';

            //if @v_nDB_DebugLevel IS NULL
            //BEGIN
            // ------------------------------------------------------------
            // --  Insert a value into the t_eics_setup table just to
            // --  make sure that that table is loaded correctly
            // ------------------------------------------------------------
            // insert into t_eics_setup
            // (station_id, type, setting_name, setting_value_number, create_by)
            // VALUES ('0', 'SYSTEM',  'APP_DEBUG_LEVEL', 5, 'ERP' )

            // SET @v_nDB_DebugLevel = 5
            //END
             using (Entities en = new Entities())
                        {
                            en.Open();
                 
                            DbCommand cmd = en.CreateCommand(String.Format(" SELECT setting_value_number " +
                                                             "FROM t_eics_setup" +
                                                             " WHERE [type] = 'SYSTEM'"+
                                                             "  AND setting_name = 'APP_DEBUG_LEVEL'"));
                           
                            DbDataReader reader = cmd.ExecuteReader();
                 if (reader.Read())
	            {
		            _debugLevel = Convert.ToInt32( reader["setting_value_number"].ToString());
	            }
                        }

             return _debugLevel;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            btnSaveWeight();
            timer1.Enabled = false;
            //Wgh = new GetScale();


        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //Wgh = new GetScale();
            this.Dispose();
        }
        private void txtPallet_TextChanged(object sender, EventArgs e)
        {
            CelWeight(txtPallet.Text, txtGross.Text);
            if (_sumResutl > 0)
            {
                btnSave.Enabled = true;
                // btnSave.Focus();
            }
        }

        private void txtGross_TextChanged(object sender, EventArgs e)
        {
            CelWeight(txtPallet.Text, txtGross.Text);
            if (_sumResutl > 0)
            {
                btnSave.Enabled = true;
                // btnSave.Focus();
            }
        }

        private void txtTare_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), _regOfTareGrossPallet)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }   
        }


        private void CelWeightTare_KeyPress(string palletInput, string grossInput, string tareInput)
        {
            try
            {
                if (palletInput.Equals(string.Empty)
               || grossInput.Equals(string.Empty))
                {
                    //
                }
                else
                {
                    int pallet = Convert.ToInt32(palletInput);
                    double gross = Convert.ToInt64(grossInput);
                    double tare = Convert.ToInt64(tareInput);





                    _sumResutl = 0;
                    double mulResutl = 0;

                    mulResutl = 1 * tare;
                    _sumResutl = gross - mulResutl;


                    //txtTare.Text = String.Format("{0:#,##0}", mul);
                    txtNet.Text = string.Format("{0:#,##0}", _sumResutl);
                }
            }
            catch
            {

                // throw;
            }
        }

        private void txtPallet_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), _regOfTareGrossPallet)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }       
        }

        private void txtGross_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), _regOfTareGrossPallet)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }       
        }
        #endregion

        #region private methods
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool baseResult = base.ProcessCmdKey(ref msg, keyData);
            if (keyData == (Keys.F1))
            {

                ReadWeight();
                return true;
            }
            else if (keyData == (Keys.LButton | Keys.ShiftKey | Keys.Control))
            {
                btnSaveWeight();
                return true;
            }

            else if (keyData == (Keys.Escape))
            {

                this.Close();
            }
            else if (keyData == Keys.Tab && txtTare.Focused)
            {
                //getTare(txtPallet.Text);
                // txtGross.Focus();
                // MessageBox.Show("sss");
                CelWeightTare_KeyPress(txtPallet.Text, txtGross.Text, txtTare.Text);
                if (_sumResutl > 0)
                {
                    btnSave.Enabled = true;
                    // btnSave.Focus();
                }
                btnSave.Focus();
                return true;
            }
          



            return baseResult;
        }
        private void btnSaveWeight()
        {

            string gross = txtGross.Text;
            string tare = txtTare.Text;
            string net = txtNet.Text;
            string pallet = txtPallet.Text;
            string time = string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now);
            //string weightCount = "";
            //Weighting = Weighting + 1;
            //weightCount = Weighting.ToString();



            if (gross != string.Empty && tare != string.Empty && net != string.Empty)
            {
                //btnSave.Enabled = true;
                string[] array = new string[5] { pallet, gross, tare, net, time };
                _main.GetDataFromWeightDisplay(array);

                this.Dispose();

            }

            // Wgh = null;
        }
       /// <summary>
       /// Read weight from serialport 
       /// </summary>
        private void ReadWeight()
        {
            
            try
            {
                //  string TempWeig = "";
                // GlobalVariable.Wgh = new GetScale();
                try
                {
                    //serialPort1.PortName = GlobalVariable.WghComPort;
                    //serialPort1.ReadTimeout = 500;
                    //serialPort1.Open();

                    if (_debugLevel >= 4 )
                    {
                        using (Entities en = new Entities())
                        {
                            en.Open();
                            DbCommand cmd = en.CreateCommand("usp_LogManager");
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID",GlobalVariable.user.ApplicationID));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.user.UserName));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchLogType", "PROCESS"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchErrorCode", "INFO-EICS-0042"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchProcess", "Read Weight"));
                            cmd.Parameters.Add(en.CreateParameter("@in_dtProcessDateTime", DateTime.Now));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData1", "Calling Marvel library"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData2", GlobalVariable.WghComPort));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData3", GlobalVariable.scaleID +' ' +GlobalVariable.user.Device));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchMessage", "Start Reading Scale[O]"));
                            cmd.ExecuteNonQuery();
                        }
                    }

                    //
                    txtGross.Text = string.Format("{0:0.##}", Convert.ToInt32(GlobalVariable.Wgh.GetFromPort(GlobalVariable.WghComPort)));
                    //String.Format("{0:0.##}", Convert.ToInt32(getRawWeight()));
                    //  String.Format("{0:0.##}", Convert.ToInt32(GlobalVariable.Wgh.GetFromPort(GlobalVariable.WghComPort)));

                    if (_debugLevel >= 4)
                    {
                        using (Entities en = new Entities())
                        {
                            en.Open();
                            DbCommand cmd = en.CreateCommand("usp_LogManager");
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", GlobalVariable.user.ApplicationID));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.user.UserName));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchLogType", "PROCESS"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchErrorCode", "INFO-EICS-0042"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchProcess", "Read Weight"));
                            cmd.Parameters.Add(en.CreateParameter("@in_dtProcessDateTime", DateTime.Now));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData1", "Calling Marvel library"));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData2", GlobalVariable.WghComPort));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchData3", GlobalVariable.scaleID + ' ' + GlobalVariable.user.Device));
                            cmd.Parameters.Add(en.CreateParameter("@in_vchMessage", "Stop Reading Scale[X]"));
                            cmd.ExecuteNonQuery();

                        }
                    }
                }
                catch (Exception)
                {

                    // throw;
                }



            }
            catch (Exception)
            {

                //throw;
            }
            finally
            {

               // this.Dispose();
            }

        }


        /// <summary>
        /// check status for open buttonreadweight
        /// </summary>
        private void ReadWeightStatus()
        {
            EicsSetupComponent comp = new EicsSetupComponent();
            EicsSetup param = new EicsSetup();
            param.Device = GlobalVariable.user.Device;
            param.AppId = GlobalVariable.user.ApplicationID;
            param.UserId = GlobalVariable.user.UserID;
            List<ObjectContext> items = comp.Search(param);
            if (items != null && items.Count > 0)
            {
                foreach (ObjectContext item in items)
                {
                    if ((((EicsSetup)item).SetupType == "STATION") && (((EicsSetup)item).StationId == GlobalVariable.user.Device))
                    {
                        if (((EicsSetup)item).ValueString == "NO")
                        {
                            btnReadWeight.Enabled = false;
                            txtGross.ReadOnly = false;
                        }
                        else if (((EicsSetup)item).ValueString == "YES")
                        {
                            btnReadWeight.Enabled = true;
                            txtGross.ReadOnly = true;
                        }
                        else if (((EicsSetup)item).ValueString == "BOTH")
                        {
                            btnReadWeight.Enabled = true;
                            txtGross.ReadOnly = false;
                        }
                        break;
                    }
                }
            }
         

           
        }

        private void CelWeight(string palletInput, string grossInput)
        {
            try
            {
                if (palletInput.Equals(string.Empty)
               || grossInput.Equals(string.Empty))
                {
                    //
                }
                else
                {
                    int pallet = Convert.ToInt32(palletInput);
                    double gross = Convert.ToInt64(grossInput);





                    _sumResutl = 0;
                    double mulResutl = 0;

                    mulResutl = pallet * _Tare;
                    _sumResutl = gross - mulResutl;


                    txtTare.Text = String.Format("{0:#,##0}", mulResutl);
                    txtNet.Text = String.Format("{0:#,##0}", _sumResutl);
                }
            }
            catch
            {

                // throw;
            }


        }
        /// <summary>
        /// get value default tare and weight from DB
        /// </summary>
        private void default_tare_weight()
        {
            try
            {
                string default_tare_weight = "";
                EicsSetupComponent comp = new EicsSetupComponent();
                EicsSetup param = new EicsSetup();
                param.Device = GlobalVariable.user.Device;
                param.AppId = GlobalVariable.user.ApplicationID;
                param.UserId = GlobalVariable.user.UserID;
                List<ObjectContext> items = comp.Search(param);
                if (items != null && items.Count > 0)
                {
                    foreach (ObjectContext item in items)
                    {
                        if (((EicsSetup)item).SettingName == "DEFAULT_TARE")
                        {
                            default_tare_weight = ((EicsSetup)item).ValueNumber.ToString();
                            txtTare.Text = default_tare_weight;
                            _Tare = Convert.ToInt32(default_tare_weight);
                            break;
                        }
                    }
                }

                //SqlCommand cmd = new SqlCommand("SELECT setting_value_number FROM t_eics_setup Where setting_name = 'DEFAULT_TARE'", sqlCon);
                //SqlDataAdapter DA = new SqlDataAdapter(cmd);
                //sqlCon.Open();
                //SqlDataReader reader3 = cmd.ExecuteReader();
                //if (reader3.Read())
                //{
                //    default_tare_weight = reader3["setting_value_number"].ToString();
                //    txtTare.Text = default_tare_weight;
                //    Tare = Convert.ToInt32(default_tare_weight);
                //}
                //else
                //{
                //    sqlCon.Close();
                //}
                //sqlCon.Close();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }

        private void get_com_port()
        {
            try
            {
                //string default_tare_weight = "";
                EicsSetupComponent comp = new EicsSetupComponent();
                EicsSetup param = new EicsSetup();
                param.Device = GlobalVariable.user.Device;
                param.AppId = GlobalVariable.user.ApplicationID;
                param.UserId = GlobalVariable.user.UserID;
                List<ObjectContext> items = comp.Search(param);
                if (items != null && items.Count > 0)
                {
                    foreach (ObjectContext item in items)
                    {
                        if (((EicsSetup)item).SettingName == "SCALE_PORT" && ((EicsSetup)item).StationId == GlobalVariable.user.Device)
                        {
                            GlobalVariable.WghComPort = ((EicsSetup)item).ValueString;
                            break;
                        }
                    }
                }

                //SqlCommand cmd = new SqlCommand("select setting_value_string from t_eics_setup WHERE setting_name='SCALE_PORT' and Station_id=@Station1", sqlCon);
                //cmd.Parameters.AddWithValue("@Station1", GlobalVariable.Device);
                //SqlDataAdapter DA = new SqlDataAdapter(cmd);
                //sqlCon.Open();
                //SqlDataReader reader3 = cmd.ExecuteReader();
                //if (reader3.Read())
                //{
                //    GlobalVariable.WghComPort = reader3["setting_value_string"].ToString();

                //}
                //else
                //{
                //    sqlCon.Close();
                //}
                //sqlCon.Close();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }
        public double getRawWeight()
        {
            double readWeight = 0.0;
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                }
                // else
                // {
                serialPort1.PortName = GlobalVariable.WghComPort;
                serialPort1.Open();
                // }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
                // throw;
            }
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            // w = -1;
            //  serialPort1.Write("W");
            Thread.Sleep(1000);
            try
            {
                readWeight = (Convert.ToDouble(_weight.Substring(1, 5)) / 1000);
            }
            catch (Exception)
            {

                //MessageBox.Show("Error in measuring the weight");
                CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Weight_Msg_chk_weight"));


            }
            return readWeight;
        }

        private void timer1_Tick_1(object sender, EventArgs e)
        {


        }



        public void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                int length = serialPort1.BytesToRead;
                if (length > 0)
                {
                    try
                    {
                        _weight = serialPort1.ReadExisting();
                    }
                    catch (Exception)
                    {

                        // throw;
                    }
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                serialPort1.Close();
                serialPort1.Dispose();
            }
        }

        private void Weight_FormClosing(object sender, FormClosingEventArgs e)
        {
            serialPort1.Close();
            serialPort1.Dispose();
        }

        private void txtTare_Leave(object sender, EventArgs e)
        {
            CelWeightTare_KeyPress(txtPallet.Text, txtGross.Text, txtTare.Text);
            if (_sumResutl > 0)
            {
                btnSave.Enabled = true;
                // btnSave.Focus();
            }
            btnSave.Focus();
        }
        private void btnReadWeight_Click(object sender, EventArgs e)
        {
            ReadWeight();
        }


        #endregion

       
      
    }


  
}
